package com.wecan.components.oss.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.wecan.api.saasdata.OssData;
import com.wecan.base.DTO.base.KeyDTO;
import com.wecan.base.PO.Oss;
import com.wecan.base.enums.OssUploadType;
import com.wecan.base.model.Result;
import com.wecan.base.utils.FileUtils;
import com.wecan.components.oss.DTO.OssPolicyDTO;
import com.wecan.components.oss.service.OSSService;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author liuzhihao
 * @Date 2022.01.15
 * @Version 1.0.0
 * @Description oss文件服务控制层
 */
@RestController
@RequestMapping(value = "/oss")
public class OSSController {

    @Autowired
    private OSSService ossService;

    @Autowired
    private OssData ossData;

    @PostMapping(value = "/image/upload/{type}")
    @SaCheckLogin
    public Result<List<JSONObject>> ossUpload(HttpServletRequest request, @PathVariable String type) {
        if (type == null) {
            return Result.failure("请不要通过违法路径上传图片！");
        }
        OssUploadType ossUploadType = OssUploadType.getNameByCode(NumberUtils.toInt(type));
        if (ossUploadType == null) {
            return Result.failure("未找到合适的资源上传类型");
        }
        List<MultipartFile> multipartFiles = ((MultipartHttpServletRequest) request).getFiles("file");
        List<JSONObject> result = new ArrayList(multipartFiles.size());
        multipartFiles.forEach(multipartFile -> {
            String fileAllName = multipartFile.getOriginalFilename();
            String fileType = fileAllName.substring(fileAllName.lastIndexOf(".") + 1);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 最后上传生成的文件名
            String uploadFileName = uuid + "." + fileType;
            SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
            // oss中的文件名
            String dateStr = date.format(new Date());
            String objectName = ossUploadType.getDesc() + dateStr + "/" + uploadFileName;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(FileUtils.getContentType(fileType));
            ossService.uploadFile(objectName, objectMetadata, multipartFile);
            Oss oss = new Oss();
            oss.setUniqueKey(objectName);
            oss.setName(fileAllName);
            ossData.insert(oss);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("fileKey", ossUploadType.getProtocol() + objectName);
            jsonObject.put("fileType", fileType);
            jsonObject.put("fileName", fileAllName);
            result.add(jsonObject);
        });
        return Result.content(result);
    }

    @PostMapping(value = "/image/delete")
    @SaCheckLogin
    public Result<Boolean> ossDelete(@RequestBody @Valid KeyDTO keyDTO) {
        Long id = keyDTO.getId();
        boolean result = ossData.delete(id);
        return Result.content(result);
    }

    @PostMapping(value = "/ali/policy")
    @SaCheckLogin
    public Result<JSONObject> getPolicy(@RequestBody @Valid OssPolicyDTO ossPolicyDTO) {
        OssUploadType type = ossPolicyDTO.getType();
        JSONObject policy = ossService.getPolicy(type.getDesc());
        policy.put("protocol", type.getProtocol());
        Oss oss = new Oss();
        oss.setUniqueKey(ossPolicyDTO.getFileKey());
        oss.setName(ossPolicyDTO.getFileName());
        ossData.insert(oss);
        return policy == null ? Result.failure("上传失败") : Result.content(policy);
    }
}
